<template>
  <div class="login-container">
    <el-card class="login-box">
      <h2 class="title">便利店仓储管理系统</h2>
      <el-form
        :model="loginForm"
        :rules="rules"
        ref="formRef"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="loginForm.code"
            placeholder="请输入验证码"
            prefix-icon="Key"
          />
        </el-form-item>
        <div style="display: flex; justify-content: end" @click="getCode">
          <img
            style="width: 100px; height: 50px; margin: 20px 0"
            :src="codeImg"
            alt=""
          />
        </div>

        <el-button
          type="primary"
          native-type="submit"
          :loading="loading"
          class="login-btn"
        >
          登录
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { loginApi, getCodeApi } from "@/api/loginApi";
import { onMounted } from "vue";
import { convertBase64ToJpg } from "@/utils/common";
import { useRoute, useRouter } from "vue-router"; // 必须导入
import { getAllMenuApi, getMenuRoleApi } from "@/api/systemApi";
import { getRoleByIdApi } from "@/api/employeeApi";
import { getAllPermissionApi, getRoleAuthorityApi } from "@/api/roleApi";
import { useMenuStore } from "@/stores/menu";
import { useAuthStore } from "@/stores/auth";

// 存储到 Pinia
const menuStore = useMenuStore();

const route = useRoute(); // 正确获取路由对象
const router = useRouter();

interface LoginForm {
  username: string;
  password: string;
  code: string;
}
const formRef = ref();
const loading = ref(false);

const loginForm = ref<LoginForm>({
  username: "",
  password: "",
  code: "",
});

const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};

const uuid = ref("");
const codeImg = ref("https://img.picui.cn/free/2025/04/24/680a213a25eb1.jpg");

// 获取菜单列表
const getMenu = (id: number) => {
  let allMenu: any[] = [];
  getAllMenuApi().then((res) => {
    allMenu = res.data;
    console.log("全部菜单", res.data);

    getMenuRoleApi(id).then((res) => {
      // console.log("ASD", res.data);
      const menuIdsSet = new Set(
        res.data.map((item: { menu_id: any }) => item.menu_id)
      );
      // 过滤menuData，只保留menu_id在menuIdsSet中的数据
      const filteredMenus = allMenu.filter((menu: { menu_id: unknown }) =>
        menuIdsSet.has(menu.menu_id)
      );
      localStorage.setItem("menuList", JSON.stringify(allMenu));
      menuStore.setMenuTree(filteredMenus);
    });
  });
};

// 获取员工角色
const getUserRoleId = (id: number) => {
  getRoleByIdApi(id).then((res) => {
    // console.log("ASDASD", res.data[0].id);

    localStorage.setItem("userRoleId", JSON.stringify(res.data[0].id));
    getRoleAuthorityApi(res.data[0].id).then((res: any) => {
      console.log("权限", res);

      const authStore = useAuthStore();
      authStore.setPermissions(res.data.map((p: any) => p.expression));
    });
  });
};

const handleLogin = async () => {
  formRef.value.validate((valid: any) => {
    if (valid) {
      // console.log("qwe", loginForm.value);
      const data = {
        ...loginForm.value,
        uuid: uuid.value,
      };
      loading.value = true;
      loginApi(data)
        .then((res: any) => {
          console.log(res);
          if (typeof res !== "object") {
            ElMessage.error(res);
          } else {
            localStorage.setItem("userId", res.data.id);
            localStorage.setItem("userInfo", JSON.stringify(res.data));
            getUserRoleId(res.data.id);
            getMenu(res.data.id);
            loading.value = false;
            ElMessage.success("登录成功");
            // 获取重定向路径
            const redirectPath = route.query.redirect;
            // 安全跳转（防止开放重定向漏洞）
            const isValidPath = /^\/([\w-]+\/?)*$/.test(redirectPath);
            router.push(isValidPath ? redirectPath : "/home");
            getAllPermissionApi({ pageNum: 1, pageSize: -1 }).then(
              (res: any) => {
                // console.log("res", res);
                localStorage.setItem(
                  "permission",
                  JSON.stringify(res.data.list)
                );
              }
            );
          }
        })
        .catch((err) => {
          loading.value = false;
        });
    } else {
      console.log("登录失败");
      loading.value = false;
      return false;
    }
  });
};

const getCode = () => {
  getCodeApi().then((res) => {
    // console.log(res);
    codeImg.value = convertBase64ToJpg(res.data.img);
    uuid.value = res.data.uuid;
  });
};

onMounted(() => {
  getCode();
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  width: 400px;
  padding: 30px;
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
}

.login-btn {
  width: 100%;
  margin-top: 10px;
}
</style>
